package com.itheima.myiotest2;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Stream;

public class Test1 {
    public static void main(String[] args) throws IOException {
        //实现带有权重的随机点名器
        //1.创建集合进行数据的读取
        ArrayList<Student> list = new ArrayList<>();
        BufferedReader bf = new BufferedReader(new FileReader("D:\\JAVAcode\\java_code\\Stream\\myio\\src\\com\\itheima\\myiotest2\\name.txt"));
        String line;
        while ((line = bf.readLine()) != null) {
            String[] arr = line.split("-");
            Student stu = new Student(arr[0], arr[1], Integer.parseInt(arr[2]), Double.parseDouble(arr[3]));
            list.add(stu);
        }
        bf.close();

        //2.计算出所有的权重
        double weight = 0;
        for (Student stu : list) {
            weight = weight + stu.getWeight();
        }

        //3.平均分配每个人的权重
        double[] arr = new double[list.size()];
        int index = 0;
        for (Student stu : list) {
            arr[index] = stu.getWeight() / 10;
            index++;
        }

        //4.计算出每一个人的权重范围 i = i-1
        for (int i = 1; i < list.size(); i++) {
            arr[i] = arr[i] + arr[i - 1];
        }

        //5.获取到随机数
        double number = Math.random();

        int result = -Arrays.binarySearch(arr, number) - 1;
        Student stu = list.get(result);
        System.out.println(stu);
        // System.out.println(Arrays.toString(arr));
        //6.进行权重缩减
        double v = stu.getWeight() / 2;
        stu.setWeight(v);

        //7.将数据写回到文件中
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\JAVAcode\\java_code\\Stream\\myio\\src\\com\\itheima\\myiotest2\\name.txt"));
        for (Student s : list) {
            bw.write(s.toString());
            bw.newLine();
        }
        bw.close();
    }
}
